
/**
 * 公共调用模块
 * 调用例子如下：
 * define(['apps/utils'],function (utils){
 *    utils.showMsg("123");
 * });
 */
define(function(){
	var debug = false,secondNavUrl = "/levelTwo.cnbi",dataUrl = "/datas.cnbi";
	
	function mask(id){
		if(!id)id = "content";//，即将呈现结果，请稍做等候
	    $("#"+id).mask("正在努力为您加载数据");
	}
	function unmask(id){
	    if(!id)id = "content";
	    $("#"+id).unmask();
	}
	/**
	 * 把c对象的属性全部给o对象
	 */
	function applyIf(o,c){
	  if (o){
			for (var p in c){
				if (o[p] != 'undefined') {
					o[p] = c[p];
			 }
		   }
		}
	  return o;
    }
    /**
     * panel的body隐藏或显示
     */
    function  bindPanelHeaderDbClick(){
      $(".panel-heading").dblclick(function(){ 
	      var $o = $(this).next();
	      if($o.is(":hidden")){ 
	         $o.slideDown("show");//如果是隐藏的则显示 
	      }else{
	        $o.slideUp("show");//如果是显示的则隐藏
	    }
	  }); 
  };
    /**
     * 提示信息显示
     */
	function alertMsg(msg) {
		alert(msg);
	}
	
	function console(msg) {
		if(window.console){
		     window.console.info(msg);
		}else{
		    //alertMsg("还在用低级的浏览器，你已经out了！"+msg);
		}
		
	}
	function errorInfo(msg) {
		if(window.console){
		     window.console.error(msg);
		}else{
		    //alertMsg("还在用低级的浏览器，你已经out了！"+msg);
		}
	}
	/**
	 * 应用表格单行选择时的样式  
	 */
	function applyTableSingleSelectClickStyle(obj){
	   $(obj).addClass("activeReport").siblings().removeClass("activeReport");
	}
	 /**
	 * 设置localstorage
	  **/
	function setLocalStorage(key, value) {
			key = encodeURIComponent(key);
			value = encodeURIComponent(value);
			if (window.localStorage) {
				localStorage.setItem(key, value);
			} else {
				Cookie.write(key, value);
			}
      };
     /**
	 * 根据key从localstorage中取值
	 */
    function  getLocalStorage(key){
			key = encodeURIComponent(key);
			var value = window.localStorage ? localStorage.getItem(key) : Cookie.read(value);
			return decodeURIComponent(value);

        };
        
   /**
    * js获取IP 或域名
    */
	function getHost(url){
			var host = "null";
			if (typeof url == "undefined" || null == url) {
				url = window.location.href;
			}
			var regex = /^\w+\:\/\/([^\/]*).*/;
			var match = url.match(regex);
			if (typeof match != "undefined" && null != match) {
				host = match[1];
			}
			return host;
     };
     /**
      * 获取工程名称
      */
    function  getProjectName() {
	     var strFullPath = window.document.location.href, strPath = window.document.location.pathname, 
	     pos = strFullPath.indexOf(strPath), prePath = strFullPath.substring(0, pos), 
	     postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
	      return postPath;
    };
    /**
	* 获取本工程完整路径 如：http://192.168.1.118:8087/cnbi-web/
	*/
    function getBasePathUrl () {
	       return "http://" + getHost() + getProjectName() + "/";
    };
   
	/**
	* author gjx
    * 设置导航条显示的方法
    */
	function levelNav(bean){
	        var $nav = $(".breadcrumb > li[class=active]"), //活动导航条对象
		        navLevel =$nav.attr("level")-0, //活动导航条level的值
		        beanLevel = bean["level"]-0,
		        size =$("li[level="+bean["level"]+"]").size();//此类级别导航条记录数
		    if(beanLevel < navLevel){
			   for(var i=beanLevel+1;i<navLevel+1;i++){//4//6
			      $("li[level="+i+"]").eq(0).remove();
			   }
			   $("li[level="+beanLevel+"]").empty().addClass("active").text(bean.sname);
			}else if(beanLevel == navLevel){
				return;
			}else{
			      var af = '<a href="'+$nav.attr("href")+'">'+$nav.text()+'</a>';
		          $nav.text('').append(af).removeClass("active");
		          $nav.after('<li level="'+bean["level"]+'" scode="'+bean.scode+'" class="active" href="javascript:;">'+bean["sname"]+'</li>');
		    }
        
	};
	function getDimParams(arr){
		if(arr){
		  dimArr = arr;
		}
    	var bean={};
    	for(var i=0,len=dimArr.length;i<len;i++){
    	    bean[dimArr[i]] = $("#"+dimArr[i]).val();
    	}
    	return bean;
    };
    var cls = Utils.cls;
    function styleChange(obj){
         $(obj).addClass(cls).siblings().removeClass(cls).addClass("btn-default");
    }
    function otherDimShow(){
        $("#main2").fadeIn("slow").siblings().fadeOut("fast");
    }
    function tableRowClick(){
	      $("tbody >tr").bind("click",function(){
	            applyTableSingleSelectClickStyle(this);//表格单行选择时调用
	            $("#options>a").removeClass("disabled");
	      });
    }
    /**
     * 判断客户机的平台
     */
    function browserRedirect() { 
		var sUserAgent= navigator.userAgent.toLowerCase(),
		 bIsIpad= sUserAgent.match(/ipad/i) == "ipad",
		 bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os",
		 bIsMidp= sUserAgent.match(/midp/i) == "midp",
		 bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4",
		 bIsUc= sUserAgent.match(/ucweb/i) == "ucweb",
		 bIsAndroid= sUserAgent.match(/android/i) == "android",
		 bIsCE= sUserAgent.match(/windows ce/i) == "windows ce",
		 bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile";
		if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) { 
		   // window.location.href= 'http://url/mobile.html'; 
		} else { 
		  // window.location= 'http://url/pc.html'; 
		} 
     }
     /**
      * 获取客户机浏览器类型名称  版本号
      */
    function brower(){
    	var  name = "";
    	if($.browser.msie){
    	     name = "IE";
    	}else if($.browser.mozilla){
    	    name = "FireFox";//webkit 
    	}else if($.browser.webkit){
    		name = "Webkit";//webkit 
    	}else if($.browser.opera){
    		name = "Opera";//webkit 
    	}
         return {
             name:name,
             version:$.browser.version
         };
    }
    /**
     * 处理IE9  table空行空行样式 
     */
     function getTableDatas(msg){
     	var bean = brower();
     	if (bean.name == "IE" && bean.version === '9.0'){
		    return  msg.replace(/>\s+(?=<\/?(t|c)[hardfob])/gm,'>');
		}
        return msg;
     }
    /**
     * 执行查询方法
     */
    function exeuteQuery(bean){
        var ss = Utils.bean;
        applyIf(bean,ss);
        var scode = bean.scode;
        bean["level"] = 3;
        mask();
        function success(msg){//response_html = response_html.replace(/td>\s+<td/g,'td><td');
        	 $("#info").remove();
        	//  msg= msg.replace(/td>\s+<td/g, 'td><td');
        	  msg = getTableDatas(msg);
        	 // console(msg);
			 $("#"+bean["tableId"]).empty().append(msg);
			 unmask();
			 if(scode.indexOf("report") != -1){
			    tableRowClick();
			 }
		}
		var url = getBasePathUrl() + bean.spcode+secondNavUrl;
        ajax({url : url,dataType : 'html',data :bean,success:success});
    }
    /**
     * select 事件绑定
     */
	function dimSelectEventBind(dimArr,query){
    	for(var i=0,len=dimArr.length;i<len;i++){
    		var dim = dimArr[i];
    	  $("#"+dim).unbind();  
    	  console("给Select--"+dim+"绑定了事件--->");
    	  $("#"+dim).bind("change",function(){
    	  	  dim = $(this).attr("id");
    	  	  var obj = $("dd[name="+dim+"]").find("a[scode="+$(this).val()+"]");
    	  	   obj = obj.eq(0);
    	  	   var params = getDimParams(dimArr);
    	  	   if(!query){
    	  	      exeuteQuery(params);
    	  	   }else{
    	          query.call(this,params);
    	       } 
    	       styleChange(obj);
    	  });
    	}
    }
     /**
     * A组件事件
     * param obj Dom对象
     */
    function dimAEventBind(dimArr,query){
    	for(var i=0,len=dimArr.length;i<len;i++){
    		  console("给A--"+dimArr[i]+"绑定了事件--->");
    		$("dd[name="+dimArr[i]+"] >a").unbind(); 
    	    $("dd[name="+dimArr[i]+"] >a").click(function(){
	        if(!$(this).hasClass(cls)){
	           styleChange(this);
	        }
	        var  dim = $(this).parent().attr("name");
	         $("#"+dim).val($(this).attr("scode"));
	         var params = getDimParams(dimArr);
	          if(!query){
    	  	      exeuteQuery(params);
    	  	   }else{
    	         query.call(this,params);
    	       } 
	     });
    	}
     };
     /**
     * 导航条事件绑定
     */
    function navEventBind(){
      $("li[level=2]").unbind();
      $("li[level=2]").bind("click",function(){
      	     // alert("导航条事件绑定");
	          $("#main1").fadeIn("slow").siblings().fadeOut("fast");
	      	  if(Utils.bean["spcode"] == "report"){
	    	        $("body").eq(0).css("overflow","auto");
	    	   }
	      	  levelNav(Utils.bean);
	      });
   }
     function getDimArrByMap(map){
        var dimArr = [];
         for(var key in map){//JSON.parse(key)
         	var field = eval("("+key+")")["field"];
		    dimArr.push(field);
		  }
		  return dimArr;
     }
    /**
     * 维度组件事件
     * param obj Dom对象
     */
	 function  dimComponentClick(map,exeuteQuery){//parseJSON
    	var dimArr = getDimArrByMap(map);
		    dimSelectEventBind(dimArr,exeuteQuery);
		    dimAEventBind(dimArr,exeuteQuery);
     };
     
	 /**
     * 视图改变
     */
    function viewChange(){
	   	var viewId = "View";
		$("#listId" + viewId).hide();
		$("#largeId,#listId").bind("click", function(){
		    var id = $(this).attr("id") + viewId;
			if(!$(this).hasClass("active")){
				$(this).addClass("active").siblings().removeClass("active");
				$("#" + id).fadeIn().siblings().fadeOut();
			}
		  
		});
    };
    var outimeCode = 911;
	/**
	 * 默认的错误事件处理
	 */
	function error(msg){
		if(msg.status != outimeCode){
		  var text = "正在开发中!错误编码：【"+msg.status +"】你懂的！亲！";
           alertMsg(text);
		}
		//unmask();
	};
	/**
	 * ajax 事件  请注意：成功 失败函数可传过来的
	 */
	function ajax(bean){
		if(!bean.dataType){bean.dataType = "json";}
		if(!bean.error){bean.error = error;}
		if(bean.async == undefined){bean.async = true;}
		 $.ajax({
				type : "POST",
				url : bean.url,
				data : bean.data,
				success : bean.success,
				dataType : bean.dataType,
				error : bean.error,
				async : bean.async
		   });
	     };

	 /**
	  * 找开二级数据页面
	  */
	function openNavlevelTwo(bean){
		var success = bean.success;
		if(!bean.success){
			 success  = function success(msg){
				levelNav(bean);
				$("#"+bean["domId"]).empty().append(msg);
				viewChange();
				dimComponentClick(Utils.dimMapJson);
			 };
		}else{
		   delete bean.success;
		}
	    var url = getBasePathUrl() + bean.spcode+secondNavUrl;
	    ajax({url : url,dataType : 'html',data :bean,success:success});
	};
	 /**
         * 打开一个窗口的方法
     */
	function openWin(bean){
			 var url = bean.url+"upload.cnbi?read=1&path="+bean.path+encodeURI(bean.sname)+bean.ext,
			 width = 1080,height = 600;
			 if(!bean.width){
			  height = bean.height;
			 }
			 if(!bean.height){
			  width = bean.width;
			 }
			 var x = screen.width/2 - width/2,
			 y = screen.height/2 - height/2;
            window.open(url, '_blank','height='+height+',width='+width+',left='+x+',top='+y);
    };
    /**
     * 改变iframe的src
     */
    function changeIframe(){
    
    }
   
     /**
     * 超时监听
     */
    function timeoutListener(){
         $.ajaxSetup({
					contentType : "application/x-www-form-urlencoded;charset=utf-8",
					complete : function(xhr, textStatus) {
						if (xhr.status == 911) {
							alertMsg("没有发现可用的用户登录的信息或会话已经销毁！请重新登录！");
							window.location = getBasePathUrl();// 返回应用首页
							return;
						}
			}
		});
    };
    /**
     * 悬浮移出事件
     */
    function regionHover(){
         $("#largeIdView >div>li").hover(function (){ // hover in
         $(this).find(".thumbnail").css("background","#DBDBDB");
          }, function (){// hover out
         $(this).find(".thumbnail").css("background","#ffffff");
         });
    };
    var scope = this;
     /**
     * 事件绑定
     */
    function eventBind (obj){//$("input[name='newsletter']")
	    $("a[level=2]").click(function(){
	    	mask();
	    	var text = $(this).attr("text"),
	         bean = {scode:$(this).attr("scode"),spcode:$(this).attr("spcode"),sname:text,level:$(this).attr("level")};
	         if(obj && obj["success"]){
	            bean["success"] = obj["success"]
	         }
	         if(Utils.pageBean.scode == "table"){
	         	var dimHelp = $(this).attr("field").split("_");
	         	 obj["subject"] = dimHelp[1];
	         	 obj["dimarr"] = dimHelp[0];
	         	 obj["showdim"] = dimHelp[0];
	         }else{
	           if(Utils.pageBean.scode == "dash"){
	           	  var id = $(this).parent().parent().parent().parent().parent().parent().parent().attr("id");
	           	  obj["dimarr"] = id;
	           }
	         }
	          applyIf(bean,obj);// 把所有obj变量的所有属性都 给bean变量
	          Utils.bean = bean;
	          openNavlevelTwo(bean);
	    });
	    regionHover();
	    
    };
    function setSelect(obj){
       if(!$(obj).hasClass(cls)){
		        $(obj).addClass(cls)
	  }
  	}
	 function removeSelect(obj){
	     if($(obj).hasClass(cls)){
			   $(obj).removeClass(cls).addClass("btn-default");
		 }
	  }
	  
	 function getDimInfo(dim){
      var dimLen = 0,value=[];
      $("dd[name="+dim+"] >a").each(function(index,o){
	     if($(o).hasClass(cls)){
	       dimLen++;
	       value.push({scode:$(o).attr("scode"),name:$(o).text()});
	     }
      });
      var dimName = $("dd[name="+dim+"] >a").parent().prev().text();
      return {dim:dim,size:dimLen,dimName:dimName,value:value};
    }
	  
	return {
		   debug:debug,
		   openNavlevelTwo:openNavlevelTwo,
		   levelNav:levelNav,
		   setLocalStorage : setLocalStorage,
           getLocalStorage :getLocalStorage,
		   alertMsg :alertMsg,
           getBasePathUrl : getBasePathUrl,
		   openWin:openWin,
		   ajax:ajax,
		   eventBind:eventBind,
		   viewChange:viewChange,
		   console:console,
		   applyIf:applyIf,
		   dimComponentClick:dimComponentClick,
		   bindPanelHeaderDbClick:bindPanelHeaderDbClick,
		   getDimArrByMap:getDimArrByMap,
		   getDimParams:getDimParams,
		   applyTableSingleSelectClickStyle:applyTableSingleSelectClickStyle,
		   cls:cls,
		   secondNavUrl:secondNavUrl,
		   dataUrl:dataUrl,
		   otherDimShow:otherDimShow,
		   navEventBind:navEventBind,
		   styleChange:styleChange,
		   getDimParams:getDimParams,
		   errorInfo:errorInfo,
		   setSelect:setSelect,
		   removeSelect:removeSelect,
		   mask:mask,
		   unmask:unmask,
		   tableRowClick:tableRowClick,
		   getTableDatas:getTableDatas,
		   getDimInfo:getDimInfo
	}
});